package com.sencorsta.ids.core.data.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

public class RedisProvider {
	public static Jedis getJedis(String key) {
		ResourceBundle bundle = ResourceBundle.getBundle("redis");
		if (bundle == null) {
			throw new IllegalArgumentException("[redis.properties] is not found!");
		}
		
		String typePath = key+".redis.";
		int expire = Integer.valueOf(bundle.getString(typePath + "expire").trim());
		JedisPoolConfig jedisconfigA = new JedisPoolConfig();
		jedisconfigA.setMaxTotal(Integer.valueOf(bundle.getString(typePath + "pool.maxTotal").trim()));
		jedisconfigA.setMaxIdle(Integer.valueOf(bundle.getString(typePath + "pool.maxIdle").trim()));
		jedisconfigA.setMaxWaitMillis(Long.valueOf(bundle.getString(typePath + "pool.maxWaitMillis").trim()));
		jedisconfigA.setTestOnBorrow(Boolean.valueOf(bundle.getString(typePath + "pool.testOnBorrow").trim()));
		jedisconfigA.setTestOnReturn(Boolean.valueOf(bundle.getString(typePath + "pool.testOnReturn").trim()));
		
		
		JedisPool pool=null;
		if (bundle.getString(typePath + "password") == null
				|| bundle.getString(typePath + "password").trim().equals("")) {
			pool = new JedisPool(jedisconfigA, bundle.getString(typePath + "ip").trim(),
					Integer.valueOf(bundle.getString(typePath + "port").trim()), expire);
		} else {
			pool = new JedisPool(jedisconfigA, bundle.getString(typePath + "ip").trim(),
					Integer.valueOf(bundle.getString(typePath + "port").trim()), expire,
					bundle.getString(typePath + "password").trim());
		}
		Jedis jedis = pool.getResource();
		pool.close();
		return jedis;
	}

	public static void Close(Jedis jedis) {
		if (jedis != null) {
			jedis.close();
		}
	}
}
